const router = require('koa-router')();
const run = require('./run');
const cfg = require('./config');

const { app: cfg_app, route: { routes } } = cfg;

// 注册用户路由  path: 应用名/控制器名/方法名
if (routes && routes.length !== 0) {
  const methods = ['get', 'post', 'put', 'patch', 'delete', 'del'];
  routes.forEach(route => {
    if(!route.method || !methods.includes(route.method)) route.method = 'all';

    // 这里如果path是个函数，那么就相当于直接执行函数内容，不需要到控制器去
    if(typeof route.path === 'function') {
      router[route.method](route.url, route.path);
      return;
    }

    // 当是路径的时候
    const paths = route.path.trim('/').split('/');
    router[route.method](route.url, async (ctx, next) => {
      ctx.application = paths[0] || cfg_app.default_app;
      ctx.controller = paths[1] || cfg_app.default_controller;
      ctx.action = paths[2] || cfg_app.default_action;
      await run(ctx, next, route.type);
    });
  });
}

// 含应用名，控制器名，方法名，如/portal/user/login
router.all('/:application/:controller/:action', async (ctx, next) => {
  setCtx(ctx);
  await run(ctx, next);
});

// 含应用名和控制器名，如/portal/user 实际访问的是/portal/user/index， portal是应用名, user是控制器
router.all('/:application/:controller', async (ctx, next) => {
  setCtx(ctx);
  await run(ctx, next);
});

// 只含应用名，如/portal 实际访问的是/portal/index/index， portal是应用名
router.all('/:application', async (ctx, next) => {
  setCtx(ctx);
  await run(ctx, next);
})

// 注册系统路由
// 首页地址 这里直接是默认值了，如/index/index/index
router.all('/', async (ctx, next) => {
  setCtx(ctx);
  await run(ctx, next);
});

function setCtx(ctx) {
  ctx.application = ctx.params.application || cfg_app.default_app;
  ctx.controller = ctx.params.controller || cfg_app.default_controller;
  ctx.action = ctx.params.action || cfg_app.default_action;
  delete ctx.params.application;
  delete ctx.params.controller;
  delete ctx.params.action;
}

module.exports = router;